try:
    import fitz
except ImportError:
    import os
    os.system('pip install PyMuPdf -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host tuna.tsinghua.edu.cn')
    import fitz

try:
    from tqdm import tqdm
except ImportError:
    import os
    os.system('pip install tqdm -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host tuna.tsinghua.edu.cn')
    from tqdm import tqdm

try:
    import requests
except ImportError:
    import os
    os.system('pip install requests -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host tuna.tsinghua.edu.cn')
    import requests

try:
    import shutil
except ImportError:
    import os
    os.system('pip install shutil -i https://pypi.tuna.tsinghua.edu.cn/simple/ --trusted-host tuna.tsinghua.edu.cn')
    import shutil

import os

url="https://s3.ananas.chaoxing.com/doc/96/0b/d6/63613d74313db5125fc8a0a8e2df2c5a/thumb/"

headers = {
    'User-Agent':'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36 QIHU 360SE'
}

res = requests.get(
    headers=headers,
    url= url,
)

def get_add_image(start, url = url, save_dir="./image"):
    i = start
    while True:
        res_url = url + str(i) + ".png"
        res = requests.get(headers=headers, url=res_url)
        if res.status_code == 404:
            break
        print("第{}张下载成功！".format(i))
        if os.path.exists(save_dir) ==False: os.makedirs(save_dir) 
        with open("{}/image_{}.png".format(save_dir, i), "wb") as fp:
            fp.write(res.content)
        i += 1
    print("下载完成")

def images_to_pdf(image_dir, outputname):
    pdf = fitz.open()
    all_images = os.listdir(image_dir)
    wrapper = tqdm(range(len(all_images)))
    for i in wrapper:
        img_path = os.path.join(image_dir, all_images[i])
        wrapper.set_description_str("正在转换{}".format(img_path))
        imgpdf = fitz.open(img_path).convert_to_pdf()
        imgpdf = fitz.open("pdf", imgpdf)
        pdf.insert_pdf(imgpdf)
    
    pdf.save(outputname)
    pdf.close()
    print("导出完成！")
    shutil.rmtree(image_dir)

if __name__ == '__main__':
    get_add_image(1)
    images_to_pdf("image", "绪论.pdf")